package com.dk.controller;

import com.alibaba.fastjson.JSONObject;
import com.dk.VO.TbUserVO;
import com.dk.constant.RecommendConstant;
import com.dk.pojo.TbCars;
import com.dk.result.Result;
import com.dk.service.Carservice;
import com.dk.service.TbUserService;
import com.dk.util.JwtUtil;
//import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Api
@ApiOperation("智能推荐")
@RestController
@RequestMapping("recommend")
public class RecommendController {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Carservice carservice;
    @Autowired
    private ESController es;

    @Autowired
    private TbUserService tbUserService;


    @PostMapping("getCarId/{id}")
    @ApiOperation(value = "用户喜欢的车辆的标签")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "车辆id", required = true, type = "path"),
            @ApiImplicitParam(name = "token", value = "单点登陆的信息",  type = "query"),
    })
    public Result getCarId(@PathVariable Long id, @RequestHeader("AuthToken") String token) {

        Claims claims = jwtUtil.parseJwt(token);
        TbUserVO user = JSONObject.parseObject(claims.getSubject(), TbUserVO.class);
        List<String> list = new ArrayList<>();
        TbCars tbCars = carservice.selectByid(id);


        long now = System.currentTimeMillis();
        redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_NUM + user.getUserid()).incrementScore(tbCars.getTagId1(), 1);
        redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_TIME + user.getUserid()).add(tbCars.getTagId1(), now);
        redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_NUM + user.getUserid()).incrementScore(tbCars.getTagId2(), 1);
        redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_TIME + user.getUserid()).add(tbCars.getTagId2(), now);
        redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_NUM + user.getUserid()).incrementScore(tbCars.getTagId3(), 1);
        redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_TIME + user.getUserid()).add(tbCars.getTagId3(), now);

        return Result.OK();
    }


    /**
     * 定时查询,更新数据
     */
    @PostMapping("countTag")
    @XxlJob(value = "countTag")
    @ApiOperation(value = "定时查询,更新数据")
    public void countTag() {
        List<TbUserVO> userVOS = tbUserService.select();
        for (TbUserVO user : userVOS) {
            //按照时间倒序取出,取出用户最新浏览的三个标签
            Set timeSet = redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_TIME + user.getUserid()).range(0, 3);
            //按照分数倒序取出
            Set countSet = redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_NUM + user.getUserid()).range(0, -1);
            for (Object o : timeSet) {
                double score = redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_NUM + user.getUserid()).score(o);
                if (score < 3) {
                    countSet.remove(o);
                }
            }
            countSet.stream().limit(3).forEach(b -> {
                int i = 3;
                redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_SHOW + user.getUserid()).add(b, i--);
            });
            timeSet.stream().forEach(b -> {
                redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_SHOW + user.getUserid()).incrementScore(b, 3);
            });
        }

    }

    /**
     * 猜你喜欢,通过用户id去redis中查询用户最近常点击的商品的分类标签去es查询相对应的商品
     *
     * @param userId 用户id
     * @return
     */
    @PostMapping("caiYouLike/{userId}")
    @ApiOperation(value = "猜你喜欢")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, type = "path")
    public Result caiYouLike(@PathVariable Long userId) {
        Set<String> range = redisTemplate.boundZSetOps(RecommendConstant.RECOMMEND_SHOW + userId).range(0, -1);
        BoolQueryBuilder boolQueryBuilder = es.xbLabelBoolQuery(range);

        Result<List> label = es.getLabel(range);
        return Result.OK().setData(label);
    }


}
